package com.demo.swingquickticket.swing.view.account;

import com.demo.swingquickticket.SwingQuickTicketApplication;
import com.demo.swingquickticket.service.AccountService;
import com.demo.swingquickticket.service.DataService;
import com.demo.swingquickticket.util.SpringUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

@Data
@EqualsAndHashCode(callSuper = true)
public class LoginPanel extends JPanel {

    private AccountService accountService = SpringUtils.getBean("accountService");

    private JLabel title;
    private JLabel loginPic;

    public LoginPanel() {
        init();
        bind();
    }

    private void init() {
        this.setLayout(new BorderLayout());
        this.title = new JLabel("二维码登入");
        this.loginPic = new JLabel("加载中。。。");
        load();

        this.add(title, BorderLayout.NORTH);
        this.add(loginPic, BorderLayout.CENTER);
    }

    private void bind() {
        this.loginPic.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                System.out.println("刷新二维码");
                load();
            }
        });
    }

    private void load() {
        this.loginPic.setText("加载中。。。");
        this.loginPic.setIcon(null);
        ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringUtils.getBean("myExecutor");
        threadPoolTaskExecutor.execute(() -> {
            String uuid = accountService.getLoginPic();
            if (uuid == null) {
                loginPic.setText("请求失败,请点击重试");
                return;
            }
            DataService.getAccount().getTemp().put("uuid", uuid);
            this.loginPic.setText("");
            String path = SwingQuickTicketApplication.class.getClassLoader().getResource("pic/login.jpg").getPath();
//            path = path.substring(1);
            System.out.println(path);
            this.loginPic.setIcon(new ImageIcon(path));
        });
    }
}
